package com.dean.service;

import com.dean.constants.DeanUiConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;


/**
 * @ClassName DeanLogPrint
 * @Description 日志打印
 * @Author dean
 * @Date 2021/10/4 9:54
 */
public class DeanLogPrintService implements Runnable {

    private final Logger logger = LoggerFactory.getLogger(DeanLogPrintService.class);
    public static long lastTimeFileSize = 0L;
    private JTextArea exeLog;

    public DeanLogPrintService(JTextArea exeLog) {
        this.exeLog = exeLog;
    }

    public void setLastTimeFileSize(long lastTimeFileSize) {
        DeanLogPrintService.lastTimeFileSize = lastTimeFileSize;
    }

    public long getLastTimeFileSize() {
        return lastTimeFileSize;
    }

    public JTextArea getExeLog() {
        return exeLog;
    }

    public void setExeLog(JTextArea exeLog) {
        this.exeLog = exeLog;
    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        lastTimeFileSize = new File(DeanUiConstants.LOG_FILE).length();
        logger.info("前台日志开启中{}", DeanUiConstants.LOG_FILE);
        while (true) {
            try {
                RandomAccessFile randomFile = new RandomAccessFile(DeanUiConstants.LOG_FILE, "r");
                randomFile.seek(lastTimeFileSize);
                String tmp = null;
                while ((tmp = randomFile.readLine()) != null) {
                    tmp = new String(tmp.getBytes("ISO-8859-1"), "utf-8");
                    exeLog.append(tmp);
                    exeLog.append("\n");
                }
                lastTimeFileSize = randomFile.length();
                Thread.sleep(5000);
            } catch (IOException e) {
                logger.error("开启前台日志失败:{}", e.getMessage(), e);
            } catch (InterruptedException e) {
                logger.error("开启前台日志线程被打断:{}", e.getMessage(), e);
            }

        }
    }

}
